<template>

  <div>
    <div style="background: #dfffb9; border:1px #77f8ff solid;width:500px;height:300px;margin:auto;margin-top: 15%;text-align: center;line-height: 270px;overflow: hidden">
      <el-button type="primary" round @click="loginTableVisible = true" >登陆</el-button>
      <el-button type="primary" round @click="registerFormVisible = true">注册</el-button>
    </div>

    <!-- Form -->

    <el-dialog title="登陆" :visible.sync="loginTableVisible">
      <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" label-width="100px" class="demo-ruleForm">
        <el-form-item
          prop="email"
          label="邮箱"
          :rules="[
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]"
        >
          <el-input v-model="loginForm.email"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input placeholder="请输入验证码" v-model="loginForm.code" maxlength="6" show-word-limit  style="width: 50%"></el-input>
          <el-button icon="el-icon-mobile-phone" @click="send('login')" style="width: 30%" type="success" :disabled="disabled=!show" >
            <span v-show="show">获取验证码</span>
            <span v-show="!show" class="count">{{count}} s</span>
          </el-button>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input placeholder="请输入账号" v-model="loginForm.account" maxlength="16" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input placeholder="请输入密码"  type="password" v-model="loginForm.pass" autocomplete="off" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitLoginForm('loginForm')">登陆</el-button>
          <el-button @click="resetLoginForm('loginForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="注册" :visible.sync="registerFormVisible">
      <el-form :model="registerForm" status-icon :rules="rules" ref="registerForm" label-width="100px" class="demo-ruleForm">
        <el-form-item
          prop="email"
          label="邮箱"
          :rules="[
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]"
        >
          <el-input v-model="registerForm.email"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input placeholder="请输入验证码" v-model="registerForm.code" maxlength="6" show-word-limit  style="width: 50%"></el-input>
          <el-button icon="el-icon-mobile-phone" @click="send('register')" style="width: 30%" type="success" :disabled="disabled=!show" >
            <span v-show="show">获取验证码</span>
            <span v-show="!show" class="count">{{count}} s</span>
          </el-button>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input placeholder="请输入账号" v-model="registerForm.account" maxlength="16" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="userName">
          <el-input placeholder="请输入昵称"  v-model="registerForm.userName" maxlength="16" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input placeholder="请输入密码"  type="password" v-model="registerForm.pass" autocomplete="off" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input  placeholder="确认密码"  type="password" v-model="registerForm.checkPass" autocomplete="off" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitRegisterForm('registerForm')">提交</el-button>
          <el-button @click="resetRegisterForm('registerForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  const TIME_COUNT = 60; //更改倒计时时间
  import axios from 'axios'
  export default {
    data() {
      var checkCode = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('验证码错误'));
        }else if(this.registerForm.code.length !== 6 && this.loginForm.code.length !== 6){
          return callback(new Error('验证码错误'));
        }else {
          callback();
        }
      };
      var checkAccount = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('账号不能为空'));
        }else {
          callback();
        }
      };
      var checkUserName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('昵称不能为空'));
        }else {
          callback();
        }
      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.registerForm.checkPass !== '') {
            this.$refs.registerForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.registerForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        loginForm: {
          email:'',
          code:'',
          account:'',
          pass: '',
        },
        registerForm: {
          email:'',
          code:'',
          account:'',
          userName:'',
          pass: '',
          checkPass: '',
        },
        rules: {
          code:[
            { validator: checkCode, trigger: 'blur' }
          ],
          account:[
            { validator: checkAccount, trigger: 'blur' }
          ],
          userName:[
            { validator: checkUserName, trigger: 'blur' }
          ],
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
        },
        loginTableVisible: false,
        registerFormVisible: false,
        show: true,  // 初始启用按钮
        count: '',   // 初始化次数
        timer: null,
      };
    },
    methods: {
      submitRegisterForm(formName) {
        this.clearTimer();
        this.$refs[formName].validate((valid) => {
          if (valid) {
            axios.post('/register',this.registerForm).then(resp => {
              if(resp.data.result){
                this.box(resp.data.msg,"注册成功")
                this.resetRegisterForm(formName)
                this.registerFormVisible = false
              }else {
                this.box(resp.data.error,"注册失败")
              }
            }).catch(err => {
              this.box(err,"注册失败")
            })
          } else {
            this.box("注册失败","注册失败")
            return false;
          }
        });
      },
      resetRegisterForm(formName) {
        this.$refs[formName].resetFields();
        this.clearTimer();
      },
      submitLoginForm(formName){
        this.clearTimer();

        this.$refs[formName].validate((valid) => {
          if (valid) {
            axios.post("/login",this.loginForm).then(resp => {
              if(resp.data.result){
                console.log(resp.data)
                // 将登录名使用vuex传递到Home页面
                this.$store.dispatch('setUser',resp.data.msg);
                this.resetLoginForm(formName)
                this.loginTableVisible = false
                this.$router.push("/online")
              }else {
                this.box(resp.data.error,"登陆失败")
                this.$store.dispatch('setUser',null)
              }
            }).catch(err => {
              this.box(err,"登陆失败")
            })
          } else {
            this.box("登陆失败","登陆失败")
            return false;
          }
        });
      },
      resetLoginForm(formName) {
        this.$refs[formName].resetFields();
        this.clearTimer();
      },
      send(url) {
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              this.clearTimer();
            }
          }, 1000)
        }
        if(url === 'login'){
          axios.get('/getlogincode',{
            params:{
              email:this.loginForm.email
            }
          }).then(resp => {
            if(!resp.data.result){
              this.box(resp.data.error,'获取验证码失败')
            }
          }).catch(err => {
            this.box(err,'获取验证码失败')
          })
        }else if(url === 'register'){
          axios.get('/getregistercode',{
            params:{
              email:this.registerForm.email
            }
          }).then(resp => {
            if(!resp.data.result){
              this.box(resp.data.error,'获取验证码失败')
            }
          }).catch(err => {
            this.box(err,'获取验证码失败')
          })
        }
      },
      clearTimer(){
        this.show = true;
        clearInterval(this.timer);  // 清除定时器
        this.timer = null;
      },
      box(msg,boxTable){
        this.$alert(msg, boxTable, {
          confirmButtonText: '确定',
          callback: action => {
            this.clearTimer();
          }
        })
      }
    }
  };
</script>

<style scoped>

</style>
